package org.enate.bloatterrorist;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.TextView;

public final class AppListFragment extends Fragment {
    private static final String TAG = "AppListFragment";
    private static String pn = "";
    protected static View v = null;
    protected static GridView gv = null;
    protected static GridItemsAdapter lia;
	protected static reloadGridView rgv;
	protected static ArrayList<PInfo> installedAppsCache;
	protected static ArrayList<PInfo> filteredAppsCache;
	private static ArrayList<PInfo> res = null;
	protected static boolean isFiltered = false;
	protected static int intFrozenTally = 0;
	private static List<ResolveInfo> lri;
	private static ResolveInfo ri;
	private static String str_appname = "";
	private static boolean appnamematch = false;
	private static ActivityInfo ai = null;
	private static Intent in = null;
	protected static String mFilter = "";
	private static int i=0, j=0, k=0;
	
    @Override
    public final View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.fragment_appoverview, container, false);
        gv = (GridView)v.findViewById(R.id.grid);
        return v;
    }
    @Override public final void onActivityCreated(Bundle savedInstanceState) {
    	super.onActivityCreated(savedInstanceState);
    	pn = Main.c.getPackageName();
        lia = new GridItemsAdapter(installedAppsCache);
		//gv.setNumColumns(Main.prefs.getInt(API.str_pref_gv_numCols, 4));
		rgv = new reloadGridView();
		rgv.execute("");
    }
    
    
    /*
    protected static void setGVMatrix(int nCols, int nRows){
		switch(API.getOrientation()){
		case Configuration.ORIENTATION_PORTRAIT:
			gv.setNumColumns(nCols==0?4:nCols);
			gv.setNumRows(nRows==0?4:nRows);
			//gv.setPageHorizontalMargin(AlmostNexusSettingsHelper.getPageHorizontalMargin(Launcher.this));
			break;
		case Configuration.ORIENTATION_LANDSCAPE:
			gv.setNumColumns(nCols==0?5:nCols);
			gv.setNumRows(nRows==0?3:nRows);
			break;
		}
    }
    */
    
    
    
    
    
    
    
    
    
    
    
	protected final static class reloadGridView extends AsyncTask<String, Integer, String>{	
		
		@Override
		protected final void onProgressUpdate(Integer... v)  {
		     super.onProgressUpdate(v);
		}
		
		@Override protected final void onPreExecute() {
			Main.pd = new ProgressDialog(Main.m);
			Main.pd.setMessage("Loading applications");
			Main.pd.setTitle("Bloat Terrorist");
			Main.pd.setIcon(R.drawable.ic_launcher);
			Main.pd.setIndeterminate(false);
			Main.pd.setMax(0);
			Main.pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			Main.pd.show();

		}
		@Override
		protected final String doInBackground(String... filter) {
			res = new ArrayList<PInfo>();
			if(filter[0].equals("")) {
				if(null!=installedAppsCache){return filter[0];}
				lri = Main.pm.queryIntentActivities(new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER), PackageManager.GET_DISABLED_COMPONENTS);
				int totalsize = lri.size();
				Main.pd.setMax(totalsize);
				for(i=totalsize; --i>=0;) {
					ri = lri.get(i);
					str_appname = ri.loadLabel(Main.pm).toString();
					Main.pd.setProgress(totalsize-i);
					if (!(ri.activityInfo.packageName).equals(pn)) {
						PInfo pinfo = new PInfo();
						pinfo.appname = str_appname;
						pinfo.pname = ri.activityInfo.packageName;
						pinfo.icon = ri.loadIcon(Main.pm);
						pinfo.launchIntent = API.getLaunchIntentByPname(pinfo.pname);
						pinfo.hasLaunchIntent = pinfo.launchIntent == null ? false : true;
						pinfo.ai = API.getActivitiesByPname(pinfo.pname);
						pinfo.appEnabled = API.boolApplicationEnabled(pinfo.pname);
						try {pinfo.isSystemApp = (Main.pm.getApplicationInfo(pinfo.pname, 0).FLAG_SYSTEM==1?true:false);} 
						catch (NameNotFoundException e){pinfo.isSystemApp = false;}
						res.add(pinfo);
					}
				}
				Collections.sort(res);
				installedAppsCache = res;
				lia = new GridItemsAdapter(installedAppsCache);
			}
			else {
				final int ps = installedAppsCache.size();
				Main.pd.setMax(ps);
				for (i=ps;--i>=0;) {
					Main.pd.setProgress(ps-i);
					PInfo p = installedAppsCache.get(i);
			        str_appname = p.appname;
					Main.pd.setProgress(ps-i);
		       		if(
		       			str_appname.toLowerCase().contains(filter[0].toLowerCase()) || 
		       			str_appname.toLowerCase().contains(filter[0].toLowerCase()) ||
		       			p.pname.toLowerCase().contains(filter[0].toLowerCase())
		       		){appnamematch=true;}
		       		else{
		       			if(filter[0].equals("Frozen Apps") && !p.appEnabled){appnamematch=true;}
		       			else if(filter[0].equals("System Apps") && p.isSystemApp){appnamematch=true;}
		       			else if(filter[0].equals("User Apps") && !p.isSystemApp){appnamematch=true;}
		       			else {appnamematch=false;}
		       		}
		        	if(appnamematch){
		        		PInfo newInfo = new PInfo();
		        			newInfo.appname = str_appname;
		        			newInfo.pname = p.pname;
		        			newInfo.icon = p.icon;
		        			newInfo.appEnabled = p.appEnabled;
			        		newInfo.launchIntent = p.launchIntent;
			        		newInfo.hasLaunchIntent = p.hasLaunchIntent;		
			        		newInfo.isSystemApp = p.isSystemApp;
					        newInfo.ai = p.ai;
					        res.add(newInfo);
		        	}
				}
				Collections.sort(res);
				filteredAppsCache = res;
				lia = new GridItemsAdapter(filteredAppsCache);
			}
			return filter[0];
		}
		@Override
		protected final void onPostExecute(String filter) {
			super.onPostExecute(filter);
			Main.pd.dismiss();
			gv.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {gvOnItemClick(0, view, position);}
			});
			gv.setOnItemLongClickListener(new OnItemLongClickListener(){
				@Override public boolean onItemLongClick(AdapterView<?> parentView, View view, int position, long id) {
					gvOnItemClick(1, view, position);
					return true;
				}});
			gv.setFastScrollEnabled(true);
			if(null==filter||filter.equals("")){
				isFiltered = false;
				gv.setAdapter(new GridItemsAdapter(installedAppsCache));
			}
			else{
				isFiltered = true;
				gv.setAdapter(new GridItemsAdapter(filteredAppsCache));
			}
			lia.notifyDataSetChanged();
		}
	}
	
	protected final static class GridItemsAdapter extends ArrayAdapter<PInfo> {
		private ArrayList<PInfo> arrayList;
		protected GridItemsAdapter(ArrayList<PInfo> arrayList) {
			super(Main.c, R.layout.appoverview_gvitem, arrayList);
			this.arrayList = arrayList;
		}
		public View getView(int position, View convertView, ViewGroup parent) {
			PInfo ta = arrayList.get(position);
			ViewHolder holder;
			convertView = Main.li.inflate(R.layout.appoverview_gvitem, null);
			convertView.setTag(R.id.appl, ta.appname);
			holder = new ViewHolder();	
			holder.text = (TextView) convertView.findViewById(R.id.appl);	
			holder.text.setText(ta.appname);
			ta.icon.setBounds(0, 0, 72, 72);
			holder.text.setCompoundDrawables(null,ta.icon, null, null);
			if(!ta.appEnabled) {
				intFrozenTally+=1;
				convertView.setBackgroundResource(R.color.lv_frozen);
			}
			return convertView;
		}
		private class ViewHolder {TextView text;}
	}
	
	protected static class PInfo implements Comparable<PInfo> {
		protected String appname = "";
		protected String pname = "";
		protected Drawable icon;
		protected boolean hasLaunchIntent = false;
		protected Intent launchIntent = null;
		protected boolean appEnabled = true;
		protected boolean isSystemApp = false;
		protected ActivityInfo[] ai = null;
		public int compareTo(PInfo p) {return appname.compareToIgnoreCase(p.appname);}   
	}
    
	protected static void gvOnItemClick(int pressMethod, View view, final int position){
		switch(pressMethod) {
		case 0: // item press
			if(Main.prefs.getInt(API.str_pref_gvi_pressaction, 0) == 0){buildGVI_QA(view, position);}
			else {launchApp(position);}	
			break;
		case 1: // long press
			if(Main.prefs.getInt(API.str_pref_gvi_pressaction, 0) == 0){launchApp(position);}
			else {buildGVI_QA(view, position);}
			break;
		}
	}
	
	private static void buildGVI_QA(View view, final int position) {
		QuickAction.qa = new QuickAction(Main.c, QuickAction.VERTICAL);
		QuickAction.qa.setTitle(ActionItem.action_title, (isFiltered==true?filteredAppsCache:installedAppsCache).get(position).appname);
		if((isFiltered==true?filteredAppsCache:installedAppsCache).get(position).hasLaunchIntent && (isFiltered==true?filteredAppsCache:installedAppsCache).get(position).appEnabled){QuickAction.qa.addActionItem(ActionItem.action_launch);}
		if((isFiltered==true?filteredAppsCache:installedAppsCache).get(position).appEnabled){QuickAction.qa.addActionItem(ActionItem.action_freeze);}
		else{QuickAction.qa.addActionItem(ActionItem.action_defrost);}
		QuickAction.qa.addActionItem(ActionItem.action_manage);
		QuickAction.qa.addActionItem(ActionItem.action_buildevent);
		QuickAction.qa.addActionItem(ActionItem.action_buildfilter);
		QuickAction.qa.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {			
			public void onItemClick(QuickAction source, int pos, int actionId) {
				switch(actionId){
				case API.int_action_buildevent:
					PagerAdapter.mPager.setCurrentItem(3);
					EventsFragment.loadEventsForPInfo((isFiltered==true?filteredAppsCache:installedAppsCache).get(position));
					break;
				case API.int_action_buildfilter: break; // TODO
				case API.int_action_freeze:
					Main.makeToast("Freezing "+(isFiltered==true?filteredAppsCache:installedAppsCache).get(position).appname);
					if (API.appToggle("pm disable ", (isFiltered==true?filteredAppsCache:installedAppsCache).get(position))){
						(isFiltered==true?filteredAppsCache:installedAppsCache).get(position).appEnabled = false;
						gv.getChildAt(position-gv.getFirstVisiblePosition()).setBackgroundResource(R.color.lv_frozen);
					}else{Main.makeToast("Unable to freeze "+(isFiltered==true?filteredAppsCache:installedAppsCache).get(position).pname);}
					break;
				case API.int_action_defrost:
					Main.makeToast("Defrosting "+(isFiltered==true?filteredAppsCache:installedAppsCache).get(position).appname);
					if (API.appToggle("pm enable ", (isFiltered==true?filteredAppsCache:installedAppsCache).get(position))){
						(isFiltered==true?filteredAppsCache:installedAppsCache).get(position).appEnabled = true;
						gv.getChildAt(position-gv.getFirstVisiblePosition()).setBackgroundColor(Color.BLACK);
					}else{Main.makeToast("Unable to restore "+(isFiltered==true?filteredAppsCache:installedAppsCache).get(position).pname);}
					break;
				case API.int_action_launch:
					try{Main.c.startActivity((isFiltered==true?filteredAppsCache:installedAppsCache).get(position).launchIntent);}
					catch(Exception e){					
						in = new Intent()
						.addCategory(Intent.CATEGORY_LAUNCHER)
						.setAction(Intent.ACTION_MAIN)
						.setPackage((isFiltered==true?filteredAppsCache:installedAppsCache).get(position).pname)
						.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						try {Main.c.startActivity(in);}
						catch(Exception e2) {Main.makeToast("(._.) Failed to run "+(isFiltered==true?filteredAppsCache:installedAppsCache).get(position).appname);}
					}
					break;
				case API.int_action_manage:
					Log.d(TAG,"mAL.get(position).pname ["+(isFiltered==true?filteredAppsCache:installedAppsCache).get(position).pname+"] ------------------");
					API.launchAppManagerScreen((isFiltered==true?filteredAppsCache:installedAppsCache).get(position).pname);
					break;
				}
			}
		});
		QuickAction.qa.show(view);
	}
	
	private static void launchApp(int position) {
		try{Main.c.startActivity((isFiltered==true?filteredAppsCache:installedAppsCache).get(position).launchIntent);}
		catch(Exception e){					
			in = new Intent()
			.addCategory(Intent.CATEGORY_LAUNCHER)
			.setAction(Intent.ACTION_MAIN)
			.setPackage((isFiltered==true?filteredAppsCache:installedAppsCache).get(position).pname)
			.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			try {Main.c.startActivity(in);}
			catch(Exception e2) {Main.makeToast("(._.) Failed to run "+(isFiltered==true?filteredAppsCache:installedAppsCache).get(position).appname);}
		}	
	}
	
	
	
	
	
	
    @Override public void onSaveInstanceState(Bundle outState) {super.onSaveInstanceState(outState);}

    
    
    
    
    
    
    
    
    
    

}